package stark;

import java.util.Scanner;

public class stackDemo {
    public static void main(String[] args) {
        //测试
        Arraystack arrayStack = new Arraystack(4);
        String key = "";
        boolean loop = true;
        Scanner scanner = new Scanner(System.in);

        while (loop) {
            System.out.println("show:显示数据");
            System.out.println("exit:退出程序");
            System.out.println("push:添加数据");
            System.out.println("pop:取出数据");
            System.out.println("请输入选择");
            key = scanner.next();
            switch (key) {
                case "show":
                    arrayStack.list();
                    break;
                case "push":
                    System.out.println("请输入一个数字");
                    int value;
                    value = scanner.nextInt();
                    arrayStack.push(value);
                    break;
                case "pop":
                    try {
                        int res = arrayStack.pop();
                        System.out.println("数据是" + res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    scanner.close();
                    loop = false;
                    break;
            }
        }
        System.out.println("程序退出");

    }


}
class Arraystack {//定义一个栈
    private int maxsize; //栈
    private int[] stack; //数组 数组模拟栈
    private int top = -1; //top表示栈顶，初始化为-1


    public Arraystack(int maxsize) {
        this.maxsize = maxsize;
        stack = new int[this.maxsize];
    }

    public boolean isFull() { //栈满
        return top == maxsize - 1;

    }

    public boolean isEmpty() { //栈空
        return top == -1;
    }

    public void push(int value) { //入栈
        if (isFull()) {
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = value;
    }

    public int pop() { //出栈
        if (isEmpty()) {
            throw new RuntimeException("栈空，没有数据");
        }

        int value = stack[top];
        top--;
        return value;
    }

    //显示栈的情况
    public void list() {
        if (isEmpty()) {
            System.out.println("栈空");

        }
        for (int i = top; i >= 0; i--) {
            System.out.println(stack[i]);

        }
    }

}
